package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"time"
)

type FailedMessage struct {
	QueueName string    `json:"queue_name"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
}

// 获取备份路径
func getBackupPath() string {
	return GlobalConfig.Backup.Path
}

func backupMessage(queueName, message string) error {
	failedMsg := FailedMessage{
		QueueName: queueName,
		Message:   message,
		Timestamp: time.Now(),
	}

	data, err := json.Marshal(failedMsg)
	if err != nil {
		return err
	}

	backupPath := getBackupPath()
	// 确保备份目录存在
	os.MkdirAll(backupPath, 0755)

	filename := filepath.Join(backupPath, fmt.Sprintf("%d.json", time.Now().UnixNano()))
	return os.WriteFile(filename, data, 0644)
}

func retryFailedMessages() error {
	backupPath := getBackupPath()
	files, err := filepath.Glob(filepath.Join(backupPath, "*.json"))
	if err != nil {
		return err
	}

	for _, file := range files {
		data, err := os.ReadFile(file)
		if err != nil {
			continue
		}

		var failedMsg FailedMessage
		if err := json.Unmarshal(data, &failedMsg); err != nil {
			continue
		}

		// 尝试重新推送到Redis
		if err := pushToRedis(failedMsg.QueueName, failedMsg.Message); err == nil {
			// 推送成功后删除备份文件
			os.Remove(file)
		}
	}

	return nil
}
